package auctionClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import org.bouncycastle.util.encoders.Base64;

public class TcpConnection {
	
	private  int tcpPort;
	private  InetAddress host;
	
	private  Socket clientSocket;
	private  PrintWriter out;
	private  BufferedReader in;
	
	public TcpConnection(int tcpPort, InetAddress host){
		this.tcpPort=tcpPort;
		this.host=host;		
	}
    
	public void connect() throws IOException{

			
			clientSocket=new Socket(host,tcpPort);
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            
	}
	
	public void close(){
		try {
			out.close();
			in.close();
			clientSocket.close();
		} catch (IOException e) {
			System.out.println("I/O exception at client side socket .close()");
		}
	}
	public byte[] getMessage(){
		try {
			String messageBase64 = in.readLine();
			byte[] message = Base64.decode(messageBase64);
			return message;
		} catch (IOException e) {
			return "I/O Read Error at client Side at the Socket".getBytes();
		}
	}
	
	public void appendMessage(byte[] message){
		byte[] messageBase64 = Base64.encode(message);
		out.println(new String(messageBase64));
	}
	public int getTcpPort(){
		return tcpPort;
	}
	
	public InetAddress getHost(){
		return host;
	}
	public boolean isBound(){
		return this.clientSocket.isBound();
	}

}
